﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Data.SQLite;

namespace SqliteManager.SQLite3
{
    /// <summary>
    /// 所有可以读取出来的数据基类
    /// </summary>
    public class DataBaseReader
    {

        public static T Read<T>(SQLiteDataReader r) where T:new()
        {
            PropertyInfo pi = null;
            FieldInfo fi = null;
            Type t = typeof(T);
            T obj = new T();
            FieldInfo[] fies = t.GetFields();
            PropertyInfo[] proes = t.GetProperties();

            while(r.Read())
            {
                int count = r.FieldCount;
                if(count<=0)
                {
                    continue;
                }

                for(int i = 0;i<count;i++)
                {
                    string key = r.GetName(i);
                    if (fies.Length > 0)
                    {
                        fi = fies.FirstEx(f => f.Name == key);

                        if(fi!=null)
                        {
                            fi.SetValue(obj, r.GetValue(i));
                            continue;
                        }
                    }else if(proes.Length>0)
                    {
                        pi = proes.FirstEx(f => f.Name == key);

                        if (pi != null)
                        {
                            pi.SetValue(obj, r.GetValue(i),null);
                            continue;
                        }
                    }else
                    {
                        Logger.Log($"{key} field not in {t}");
                    }
                }
            }

            return obj;
        }
    }
}
